from rest_framework import viewsets, filters, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from .models import Project, Version, ProductLine
from .serializers import ProjectSerializer, VersionSerializer, ProjectListSerializer, ProductLineSerializer

class ProjectViewSet(viewsets.ModelViewSet):
    """项目视图集"""
    queryset = Project.objects.all().order_by('-created_at')
    serializer_class = ProjectSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['project_type', 'is_active', 'creator', 'department']
    search_fields = ['name', 'description']
    ordering_fields = ['created_at', 'updated_at', 'name']
    permission_classes = [permissions.AllowAny]
    
    @action(detail=False, methods=['get'], url_path='project-list')
    def project_list(self, request):
        """项目列表（用于项目管理页面）"""
        queryset = self.get_queryset()
        serializer = ProjectListSerializer(queryset, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['get'], url_path='versions')
    def project_versions(self, request, pk=None):
        """获取项目的所有版本"""
        project = self.get_object()
        versions = project.versions.all().order_by('-created_at')
        serializer = VersionSerializer(versions, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['get'], url_path='cases-count')
    def cases_count(self, request, pk=None):
        """获取项目的用例总数"""
        project = self.get_object()
        from cases.models import TestCase
        count = TestCase.objects.filter(version__project=project).count()
        return Response({'cases_count': count})

class VersionViewSet(viewsets.ModelViewSet):
    """项目版本视图集"""
    queryset = Version.objects.all().order_by('-created_at')
    serializer_class = VersionSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['project', 'is_current']
    search_fields = ['version_number', 'description']
    ordering_fields = ['created_at', 'updated_at', 'version_number']
    permission_classes = [permissions.AllowAny]
    
    @action(detail=True, methods=['get'], url_path='cases')
    def version_cases(self, request, pk=None):
        """获取版本的所有用例"""
        version = self.get_object()
        from cases.models import TestCase
        cases = version.test_cases.all().order_by('case_id')
        from cases.serializers import TestCaseListSerializer
        serializer = TestCaseListSerializer(cases, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['post'], url_path='set-current')
    def set_current(self, request, pk=None):
        """设置为当前版本"""
        version = self.get_object()
        # 先将同项目的其他版本设置为非当前版本
        Version.objects.filter(project=version.project).update(is_current=False)
        # 将当前版本设置为当前版本
        version.is_current = True
        version.save()
        return Response({'status': 'success', 'message': '已设置为当前版本'})

class ProductLineViewSet(viewsets.ModelViewSet):
    """产品线视图集"""
    queryset = ProductLine.objects.all().order_by('-created_at')
    serializer_class = ProductLineSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_active']
    search_fields = ['name', 'description']
    ordering_fields = ['created_at', 'updated_at', 'name']
    permission_classes = [permissions.AllowAny]

# 创建API路由
from django.urls import path, include
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'projects', ProjectViewSet)
router.register(r'versions', VersionViewSet)
router.register(r'product_lines', ProductLineViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
